<?php

namespace Biz\Resources\App;

use Lumen\Http\Resources\Json\Resource;
use Biz\Resources\Passport\ClientResource;

/**
 * AppSiteResource.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class AppSiteResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'uid'         => $this->uid,
            'name'        => $this->name,
            'domain'      => $this->domain,
            'description' => $this->description,
            'created_at'  => $this->created_at->getTimestamp(),
            $this->mergeWhen(! is_null($this->getApp()), [
                'app' => $this->getAppResource(),
            ]),
            $this->mergeWhen($this->relationLoaded('app'), [
                'app' => $this->getAppResourceByRelation(),
            ]),
            $this->mergeWhen($this->relationLoaded('languages'), [
                'languages' => $this->getLanguages(),
            ]),
        ];
    }

    /**
     * Get app resource.
     *
     * @return AppResource|null
     */
    public function getAppResource()
    {
        if (! is_null($this->getApp())) {
            return new AppResource($this->getApp());
        }

        return null;
    }

    /**
     * Get app resource by relation.
     *
     * @return ClientResource|null
     */
    public function getAppResourceByRelation()
    {
        if ($this->relationLoaded('app')) {
            return new AppResource($this->app);
        }

        return null;
    }

    /**
     * Get app resource by relation.
     *
     * @return array|null
     */
    public function getLanguages()
    {
        if ($this->relationLoaded('languages')) {
            $languages = [];
            foreach ($this->languages as $language) {
                $languages[] = $language->lang;
            }

            return $languages;
        }

        return null;
    }
}
